import os
import json

class N4dChat:
	def __init__(self):
		'''
		Class Constructor: Initializes Messages
		'''
		
		# Define Messages as a List (empty)
		self.Messages=[]
		# Define user list
		self.userList=[]
		return None
		
	#def init


	def registerUser(self, ip, username):
		'''
		register username
		'''
		try:
			# Msg is a register formed by ip, username and message
		
			user={"ip":ip, "username": username}
			self.userList.append(user)
			return 0
		except Exception as e:
			print "except "+str(e)
			return -1

	def getUsers(self):
		try:
			return(self.userList)
		except Exception as e:
			print "except"+str(e)
			
	
	def sendMessage(self, ip, username, message):
		'''
		sends a Message to chat from user,ip
		'''
		try:
			# Msg is a register formed by ip, username and message
		
			msg={"ip":ip, "username": username, "message":message}
			self.Messages.append(msg)
		except Exception as e:
			print "except "+str(e)
			return -1
		
	#def sendMessage
	
	def getMessages(self,startMsg):
		'''
		returns messages from startMsg to last message
		'''
		try:
			# Python sublists notation: list[stat:end]
			return({"last_msg":len(self.Messages) ,"messages": self.Messages[int(startMsg):]})
		except Exception as e:
			print "except "+str(e)
			return -1
		
		return 0
		
	#def getMessages
	
	def saveChat(self, filename):
		try:
			with open("/tmp/"+filename, 'w') as outfile:
				json.dump(self.Messages, outfile)				
		except Exception as e:
			print "except "+str(e)
			return -1
		return 0
	# def saveChat
				
#class N4dChat
